<template>
    <div>
        <h1 style="text-align: left;">个人所得税税率表</h1><br>
        
        <el-form :model="formData" ref="form" :rules="rules" label-width="80px" :inline="true" style="display: flex; flex-direction: column; gap: 16px; text-align: left;">
            
            <el-form-item label="">
                
                <el-row :gutter="20" style="width: 100%;">
                    <el-col :span="12" :offset="0">
                        <span>应纳税所得额下限（元）</span>
                        <el-input v-model.number="formData.lowerLimit" type="number"></el-input>
                        <span>应纳税所得额上限（元）</span>
                        <el-input v-model.number="formData.upperLimit" type="number"></el-input>
                        <span>税率（%）</span>
                        <el-input v-model.number="formData.rate" type="number"></el-input>
                        <span>是否启用<br></br></span>
                        <el-radio-group v-model="formData.enable">
                        <el-radio label="启用">启用</el-radio>
                        <el-radio label="禁用">禁用</el-radio>
                        </el-radio-group>
                         </el-col>
                    <el-col :span="12" :offset="0">
                        
                    </el-col>                       
                </el-row>
                
                       
                                
            </el-form-item>
            <el-form-item  style="margin-top: auto; align-self: flex-start;">
                <el-button type="primary" @click="onSubmit">提交</el-button>
                
            </el-form-item>
        </el-form>
        
        
    </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
import request from '@/api/request.js'
import { ElMessage } from 'element-plus'

let emits = defineEmits(['ref-table'])

let formData = ref({
    lowerLimit: null,
    upperLimit: null,
    rate: null,
    enable: '启用'
})

// 检查区间是否冲突
const checkIntervalConflict = async () => {
    // 验证输入的区间有效性
    if (formData.value.lowerLimit === null || formData.value.upperLimit === null) {
        ElMessage.error('请填写完整的所得额区间');
        return false;
    }
    if (formData.value.lowerLimit >= formData.value.upperLimit) {
        ElMessage.error('下限不能大于等于上限');
        return false;
    }

    try {
        // 查询所有已存在的税率区间
        const res = await request({
            url: '/salary/setup/rate',
            method: 'get',
            params: {
                size: 1000, // 假设1000条足够覆盖所有区间
                current: 1
            }
        });

        if (res.code !== 200 || !res.data.records) {
            ElMessage.error('查询现有税率区间失败');
            return false;
        }

        const existingIntervals = res.data.records;
        
        // 检查每个现有区间是否存在冲突
        for (const interval of existingIntervals) {
            // 区间冲突判断逻辑：
            // 1. 新增区间包含现有区间
            // 2. 现有区间包含新增区间
            // 3. 新增区间下限在现有区间内
            // 4. 新增区间上限在现有区间内
            const hasConflict = (
                (formData.value.lowerLimit <= interval.lowerLimit && formData.value.upperLimit >= interval.upperLimit) ||
                (interval.lowerLimit <= formData.value.lowerLimit && interval.upperLimit >= formData.value.upperLimit) ||
                (formData.value.lowerLimit >= interval.lowerLimit && formData.value.lowerLimit <= interval.upperLimit) ||
                (formData.value.upperLimit >= interval.lowerLimit && formData.value.upperLimit <= interval.upperLimit)
            );

            if (hasConflict) {
                ElMessage.error(`区间冲突：已存在 [${interval.lowerLimit}, ${interval.upperLimit}] 的税率区间`);
                return false;
            }
        }

        return true;
    } catch (error) {
        ElMessage.error('检查区间冲突时发生错误');
        return false;
    }
}

const onSubmit = async () => {
    // 先检查区间冲突
    const canSubmit = await checkIntervalConflict();
    if (!canSubmit) return;

    try {
        await request({
            url: '/salary/setup/rate/insert',
            method: 'post',
            data: formData.value
        });
        ElMessage.success('提交成功');
        emits('ref-table'); // 刷新列表
        // 重置表单
        formData.value = {
            lowerLimit: null,
            upperLimit: null,
            rate: null,
            enable: '启用'
        };
    } catch (error) {
        ElMessage.error('提交失败，请重试');
    }
}
</script>

<style scoped>

</style>